package com.hds.modules.app.controller;

import com.hds.common.exception.RRException;
import com.hds.common.utils.R;
import com.hds.modules.app.annotation.Login;
import com.hds.modules.app.annotation.LoginUser;
import com.hds.modules.app.entity.ActivationCodeEntity;
import com.hds.modules.app.entity.UserEntity;
import com.hds.modules.app.entity.dto.TempUserInfo;
import com.hds.modules.app.entity.dto.UserEntityDto;
import com.hds.modules.app.enums.ActivateCode;
import com.hds.modules.app.form.LoginForm;
import com.hds.modules.app.service.ActivationCodeService;
import com.hds.modules.app.service.UserService;
import com.hds.modules.app.utils.DateUtils;
import com.hds.modules.app.utils.JwtUtils;
import com.hds.modules.sys.controller.AbstractController;
import com.hds.modules.sys.entity.base.SysCompanyEntity;
import com.hds.modules.sys.entity.base.SysMemberShipEntity;
import com.hds.modules.sys.entity.base.SysMemberShipRecordsEntity;
import com.hds.modules.sys.service.base.SysCompanyService;
import com.hds.modules.sys.service.base.SysMemberShipRecordsService;
import com.hds.modules.sys.service.base.SysMemberShipService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author guonan
 * @Email guonan@yewcn.com
 * @Description
 * @Date 2018/6/19 17:20
 */
@RestController
@RequestMapping("/app/user")
public class AppUserController extends AbstractController{

    @Autowired
    UserService userService;

    @Autowired
    private ActivationCodeService activationCodeService;

    @Autowired
    private SysMemberShipService sysMemberShipService;

    @Autowired
    private SysMemberShipRecordsService sysMemberShipRecordsService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Autowired
    private JwtUtils jwtUtils;

    @Login
    @RequestMapping("/userInfo")
    public R queryUserInfo(@LoginUser UserEntity user){

        if(user==null)return R.error(401, "请重新登录");

        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getUserId());
        map.put("status", 1);
        List<ActivationCodeEntity> list = activationCodeService.selectByMap(map);

        UserEntityDto userDto = new UserEntityDto();
        ActivationCodeEntity code = null;
        Date expireTime = null; //会员过期时间
        String companyName = null; //该激活码所属公司
        Long days = 0L;

        logger.info("code:{}", code);
        Integer levelId = null;

        // 判读该用户是否有已支付的会员升级订单
        Map<String, Object> params = this.isExistPayableOrder(user);
        logger.info("==========params:{}==========", params);
        Integer payableMaxLevel = (Integer)params.get("payableMaxLevel"); // 最高levelId
        Date payTime = (Date)params.get("payTime");

        // 有一种情况：已激活和已支付同时存在的情况，会员权益该怎么算？待解决
        logger.info("=======存在已支付的会员升级订单==等级为:{}==========", payableMaxLevel);
        if(payableMaxLevel == 0){
            if(list!=null && list.size()>0){
                code = list.get(0);
            }
            if(code == null){
                levelId = SysMemberShipEntity.LEVEL_1;
            } else {
                levelId = code.getLevelId();

                Map<String, Object> paramsMap=getDaysAndCompanyNameByCode(code);
                companyName = (String)paramsMap.get("companyName");
                days = (Long)paramsMap.get("days");
            }

        }else{
            // 该用户已激活的列表中未过期最高权益等级
            Integer activatedMaxLevel = getActivatedMaxLevel(user);
            // 该用户已支付的等级列表中未过期最高等级
            levelId = payableMaxLevel;

            logger.info("======已激活等级为activatedMaxLevel:{}=已支付的等级id：{}=========", activatedMaxLevel, levelId);

            // 如果已激活和已支付都存在未过期的等级，取最大等级
            if(activatedMaxLevel >= levelId){
                logger.info("=======已支付和已激活的的会员升级记录都存在==");
                // 根据levelId查询激活码详情
                ActivationCodeEntity codeEntity = getActivateCodeByLevelId(user, activatedMaxLevel);

                levelId = codeEntity.getLevelId();

                Map<String, Object> paramsMap=getDaysAndCompanyNameByCode(codeEntity);
                companyName = (String)paramsMap.get("companyName");
                days = (Long)paramsMap.get("days");

            }else{
                logger.info("===查询已支付会员等级记录====");
                expireTime = DateUtils.addYear(payTime, 1);
                days = DateUtils.timespaceOfDays(new Date(), expireTime);
            }


        }


        logger.info("levelId=====:{}", levelId);
        SysMemberShipEntity ship = sysMemberShipService.selectById(levelId);
        logger.info("ship=====:{}", ship);
        if(ship!=null){
            userDto.setLevel(ship);
        }
        try {
            BeanUtils.copyProperties(userDto, user);
        }catch (Exception e) {
            e.printStackTrace();
        }

        userDto.setCompanyName(companyName);
        userDto.setDays(Integer.valueOf(String.valueOf(days)));

        return R.ok().put("user",userDto);
    }


    private Map<String, Object> getDaysAndCompanyNameByCode(ActivationCodeEntity code){
        String companyName=null;
        Long days=0L;
        Date expireTime = code.getExpireTime();
        Integer companyId = code.getCompanyId();
        SysCompanyEntity company = sysCompanyService.selectById(companyId);
        if(company!=null) companyName = company.getName();
        days = DateUtils.timespaceOfDays(new Date(), expireTime);

        Map<String, Object> map=new HashMap<>();
        map.put("companyName", companyName);
        map.put("days", days);
        return map;

    }


    // 根据levelId查询激活码列表
    private ActivationCodeEntity getActivateCodeByLevelId(UserEntity user, Integer levelId) {
        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getUserId());
        map.put("status", ActivateCode.StatusEnum.ACTIVATED.getStatus());
        map.put("level_id", levelId);

        logger.info("===根据levelId查询激活码列表：{}====", map);

        Long days = 0L;

        List<ActivationCodeEntity> codes = activationCodeService.selectByMap(map);
        logger.info("==同一等级激活码列表待排序==codes:{}===:", codes);
        // 找出已支付的订单中会员等级最高的订单
        ActivationCodeEntity codeEntity = Collections.max(codes);
//        Collections.sort(codes);
        logger.info("===找出已已激活的激活列表中等级最高的激活码中有效期天数最多的====codeEntity:{}========", codeEntity.toString());

        return codeEntity!=null ? codeEntity : null;
    }

    private Integer getActivatedMaxLevel(UserEntity user) {
        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getUserId());
        map.put("status", ActivateCode.StatusEnum.ACTIVATED.getStatus());

        Integer maxLevelId = 0;

        List<ActivationCodeEntity> codes = activationCodeService.selectByMap(map);
        logger.info("====已激活的激活码列表==:{}",codes);
        // 找出已激活的激活码中会员等级最高的订单
        if(codes!=null && codes.size() > 0){
            for (ActivationCodeEntity code: codes) {
                if(code.getLevelId() > maxLevelId){
                    maxLevelId = code.getLevelId();
                }
            }
        }
        return maxLevelId;
    }

    /**
     *  判断该用户是否有已支付的会员升级订单
     * @param user
     */
    private Map<String, Object> isExistPayableOrder(UserEntity user) {
        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getUserId());
        map.put("status", SysMemberShipRecordsEntity.SUCCESS);

        Integer payableMaxLevel = 0;
        Date payTime = null;

        List<SysMemberShipRecordsEntity> records = sysMemberShipRecordsService.selectByMap(map);
        // 找出已支付的订单中会员等级最高的订单
        if(records!=null && records.size() > 0){
            for (SysMemberShipRecordsEntity record: records) {
                if(record.getLevelId() > payableMaxLevel){
                    payableMaxLevel = record.getLevelId();
                    payTime = record.getPayTime();
                }
            }
        }
        Map<String, Object> params = new HashMap<>();
        params.put("payableMaxLevel", payableMaxLevel);
        params.put("payTime", payTime);
        return params;
    }


    //@Login
    @RequestMapping("/info")
    public TempUserInfo queryUserInfoTemp(@RequestParam("mobile") String mobile){

        //登录
        LoginForm form = new LoginForm();
        form.setMobile(mobile);
        //用户登录
        long userId = userService.login(form);
        UserEntity user = userService.selectById(userId);






        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getUserId());
        map.put("status", 1);
        List<ActivationCodeEntity> list = activationCodeService.selectByMap(map);

        UserEntityDto userDto = new UserEntityDto();
        ActivationCodeEntity code = null;
        Date expireTime = null; //会员过期时间
        String companyName = null; //该激活码所属公司
        Integer levelId = null;
        Long days=0L;

        if(list!=null && list.size()>0){
            code = list.get(0);
            levelId = code.getLevelId();

            SysMemberShipEntity ship = sysMemberShipService.selectById(levelId);
            if(ship!=null){
                userDto.setLevel(ship);
            }

            expireTime = code.getExpireTime();
            Integer companyId = code.getCompanyId();
            SysCompanyEntity company = sysCompanyService.selectById(companyId);
            if(company!=null) companyName = company.getName();

            days = DateUtils.timespaceOfDays(new Date(), expireTime);
        }else{
            SysMemberShipEntity ship = sysMemberShipService.selectById(1);
            userDto.setLevel(ship);
        }





        try {
            BeanUtils.copyProperties(userDto, user);
        }catch (Exception e) {
            e.printStackTrace();
        }

        userDto.setCompanyName(companyName);
        userDto.setDays(Integer.valueOf(String.valueOf(days)));


//        String avatar = userDto.getAvatar();
//        String nickName = userDto.getNickName();
//        int couponNum = userDto.getCouponCount();
//        int existNoPayOrder = userDto.getOrderCount();
//        int isAddress = userDto.getAddressCount();
//        int isCertified = userDto.getIsCertified();
//        long uid = userDto.getUserId();
//        String phone = userDto.getMobile();
        int vipDay = userDto.getDays();

        SysMemberShipEntity level = userDto.getLevel();
        String content = level.getContent();
        int id = level.getId();
        int lev = level.getLevel();
        String logo = level.getLogo();
        String levName = level.getName();

        TempUserInfo userInfo = new TempUserInfo();
        userInfo.setCompanyName(companyName);
//        userInfo.setContactNickName(nickName);
//        userInfo.setCouponNum(couponNum);
//        if(existNoPayOrder == 0)userInfo.setExistNoPayOrder(false);
//        userInfo.setIsAddress(isAddress);
//        if(isCertified == 0){
//            userInfo.setStatus("unrecognized");
//        }
//        userInfo.setUsername(mobile);
        userInfo.setVipContent(content);
        userInfo.setVipDay(vipDay);
        userInfo.setVipId(id+"");
        userInfo.setVipLevel(lev+"");
        userInfo.setVipLogo(logo);
        userInfo.setVipName(levName);
//        userInfo.setWxUserHeadimgurl(avatar);



        return userInfo;
    }

}
